from datetime import datetime
from backend.utils import get_db_connection

# 用户模型
class User:
    """
    用户模型类
    属性:
        id: 用户ID
        username: 用户名
        email: 邮箱
        api_key: API密钥
        created_at: 创建时间
    """
    @staticmethod
    def create_table():
        """创建用户表"""
        conn = get_db_connection()
        conn.execute('''
            CREATE TABLE IF NOT EXISTS users (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                username TEXT NOT NULL,
                email TEXT NOT NULL UNIQUE,
                api_key TEXT NOT NULL UNIQUE,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
            )
        ''')
        conn.commit()
        conn.close()
        
    @staticmethod
    def insert_user(username, email, api_key):
        """
        插入新用户数据
        参数:
            username: 用户名
            email: 邮箱
            api_key: API密钥
        返回:
            插入的用户ID
        """
        conn = get_db_connection()
        try:
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO users (username, email, api_key) VALUES (?, ?, ?)",
                (username, email, api_key)
            )
            conn.commit()
            return cursor.lastrowid
        except Exception as e:
            conn.rollback()
            raise e
        finally:
            conn.close()

# 聊天记录模型
class ChatMessage:
    """
    聊天记录模型类
    属性:
        id: 记录ID
        user_id: 用户ID
        content: 消息内容
        sender: 发送者(user/ai)
        created_at: 创建时间
    """
    @staticmethod
    def create_table():
        """创建聊天记录表"""
        conn = get_db_connection()
        conn.execute('''
            CREATE TABLE IF NOT EXISTS chat_messages (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                content TEXT NOT NULL,
                sender TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users (id)
            )
        ''')
        conn.commit()
        conn.close()

# 支付信息模型
class Payment:
    """
    支付信息模型类
    属性:
        id: 支付ID
        user_id: 用户ID
        amount: 金额
        status: 支付状态
        created_at: 创建时间
    """
    @staticmethod
    def create_table():
        """创建支付信息表"""
        conn = get_db_connection()
        conn.execute('''
            CREATE TABLE IF NOT EXISTS payments (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                user_id INTEGER NOT NULL,
                amount REAL NOT NULL,
                status TEXT NOT NULL,
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                FOREIGN KEY (user_id) REFERENCES users (id)
            )
        ''')
        conn.commit()
        conn.close()

# 初始化所有表
def init_db():
    """初始化数据库表"""
    User.create_table()
    ChatMessage.create_table()
    Payment.create_table()